package com.killer.controller;

import com.killer.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@RestController
@RequestMapping("file")
public class FileController {

    @Autowired
    private FileService fileService;

    @RequestMapping("/upload")
    public String uploadFile(MultipartFile file) throws IOException {
        return fileService.uploadFile(file);
    }

    @RequestMapping("/download")
    public void download(@RequestParam("key") String key, HttpServletResponse response) throws Exception {
        InputStream inputStream = fileService.download(key);
        response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(key,"UTF-8"));
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[1024];
        int read=0;
        while ((read = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }
        outputStream.flush();
        outputStream.close();
    }

    @RequestMapping("/delete")
    public String deleteFile(@RequestParam("key") String key) throws IOException {
        fileService.deletFile(key);
        return "success";
    }
}
